package app

import (
	"net/http"

	"gitee.com/zhaokangming/tiny-ticktok/pkg/errcode"

	"github.com/gin-gonic/gin"
)

type Responser interface {
	SetCode(int)
	SetMsg(string)
}

// Response 响应结构体
type Response struct {
	Code int    `json:"status_code"`
	Msg  string `json:"status_msg"`
}

func (r *Response) SetCode(code int) {
	r.Code = code
}

func (r *Response) SetMsg(msg string) {
	r.Msg = msg
}

// WriteResponse 写入返回结果
func WriteResponse(c *gin.Context, err error, data Responser) {
	if data == nil {
		data = new(Response)
	}
	if err != nil {
		c.Set("error", err)
		coder := errcode.ParseCoder(err)
		data.SetMsg(coder.String())
		data.SetCode(coder.Code())
		if err == errcode.ErrParamTypeError {
			c.JSON(coder.HTTPStatus(), data)
			return
		}

		c.JSON(coder.HTTPStatus(), data)
		return
	}
	c.Set("resp", data)
	data.SetMsg("操作成功")
	data.SetCode(0)
	c.JSON(http.StatusOK, data)
}
